<template>
    <div class="login-container" :style="loginContainerStyle">
        <!-- 背景遮罩（增强移动端可读性） -->
        <div class="bg-overlay"></div>

        <!-- 登录卡片（自适应宽高） -->
        <div class="login-card">
            <!-- 左侧品牌区域（移动端自动隐藏或堆叠） -->
            <div class="brand-section">
                <el-image
                    class="login-logo"
                    :src="state.logoImg"
                    fit="contain"
                ></el-image>
                <span class="system-title">后台管理系统</span>
            </div>

            <!-- 右侧登录表单区域（自适应宽度） -->
            <div class="form-section">
                <el-form
                    :model="state.loginForm"
                    :rules="rules"
                    ref="loginFormRef"
                    label-width="1em"
                    class="login-form"
                    hide-required-asterisk
                >
                    <el-form-item prop="username">
                        <el-input
                            size="large"
                            v-model="state.loginForm.username"
                            prefix-icon="User"
                            placeholder="请输入用户名称"
                            :maxlength="20"
                        ></el-input>
                    </el-form-item>

                    <el-form-item prop="password">
                        <el-input
                            type="password"
                            size="large"
                            v-model="state.loginForm.password"
                            prefix-icon="Lock"
                            show-password
                            placeholder="请输入密码"
                            :maxlength="20"
                        ></el-input>
                    </el-form-item>

                    <el-form-item class="form-actions">
                        <el-checkbox
                            v-model="rememberUser"
                            class="remember-checkbox"
                        >
                            记住密码
                        </el-checkbox>
                        <el-button type="text" class="forgot-btn"
                            >忘记密码？</el-button
                        >
                    </el-form-item>

                    <el-form-item class="submit-section">
                        <el-button
                            class="login-submit"
                            size="large"
                            type="primary"
                            @click="submit"
                            :loading="submitLoading"
                        >
                            登录
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script setup>
import {
    defineComponent,
    reactive,
    ref,
    toRefs,
    onMounted,
    computed,
} from 'vue';
import { useRouter, useRoute } from 'vue-router';
import Cookies from 'js-cookie';
import { ElMessage } from 'element-plus';

// 导入资源
import logo from '@/assets/img/logo.png';
import bg from '@/assets/img/bg.jpg';

// 响应式背景样式计算
const loginContainerStyle = computed(() => ({
    backgroundImage: `url(${bg})`,
    backgroundSize: 'cover',
    backgroundPosition: 'center',
}));

// 状态管理
const state = reactive({
    loginForm: {
        username: '',
        password: '',
    },
    rememberUser: false,
    logoImg: logo,
    submitLoading: false,
    // 适配移动端的响应式状态
    isMobile: false,
});

// 表单验证规则
const rules = {
    username: [
        { required: true, message: '用户名称不能为空', trigger: 'blur' },
        { min: 2, message: '用户名至少2个字符', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
        { min: 6, message: '密码至少6个字符', trigger: 'blur' },
    ],
};

// 引用与路由
const loginFormRef = ref(null);
const router = useRouter();
const route = useRoute();

// 监听窗口尺寸变化，判断是否为移动端
const checkMobile = () => {
    state.isMobile = window.innerWidth < 768;
};

// 页面加载时初始化
onMounted(() => {
    // 初始化响应式状态
    checkMobile();
    window.addEventListener('resize', checkMobile);

    // 读取记住的密码
    if (Cookies.get('rememberUser') === 'true') {
        state.loginForm.username = Cookies.get('username') || '';
        state.loginForm.password = Cookies.get('password') || '';
        state.rememberUser = true;
    }
});

// 组件卸载时清理
const onUnmounted = () => {
    window.removeEventListener('resize', checkMobile);
};

// 登录提交处理
const isAuthenticated = ref(false);
const submit = () => {
    state.submitLoading = true;

    loginFormRef.value.validate((valid) => {
        if (valid) {
            // 处理记住密码
            if (state.rememberUser) {
                Cookies.set('rememberUser', 'true', { expires: 7 });
                Cookies.set('username', state.loginForm.username, {
                    expires: 7,
                });
                Cookies.set('password', state.loginForm.password, {
                    expires: 7,
                });
            } else {
                Cookies.remove('rememberUser');
                Cookies.remove('username');
                Cookies.remove('password');
            }
            localStorage.setItem('isAuthenticated', 'true'); // 持久化登录状态
            isAuthenticated.value = true; // 同步响应式状态
            // 模拟登录成功（实际项目替换为真实接口）
            setTimeout(() => {
                ElMessage.success('登录成功');
                router.push({ path: '/' });
                state.submitLoading = false;
            }, 500);
        } else {
            state.submitLoading = false;
            return false;
        }
    });
};
</script>

<style lang="scss">

.login-container {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
}


// 登录卡片（自适应居中）
.login-card {
    position: relative;
    z-index: 2;
    width: 90%;
    max-width: 800px;
    min-width: 300px;
    height: auto;
    min-height: 500px;
    margin: 0 auto;
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.2);
    display: flex;
    flex-direction: row; // 默认横向布局
    overflow: hidden;

    // 移动端适配：改为纵向布局
    @media (max-width: 768px) {
        flex-direction: column;
        min-height: auto;
        margin: 5vh auto;
        max-height: 90vh;
        overflow-y: auto;
    }
}

// 品牌展示区域
.brand-section {
    flex: 1;
    padding: 2rem;
    background-color: #cdcdcd;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;

    .login-logo {
        width: 60%;
        max-width: 200px;
        height: auto;
        margin-bottom: 2rem;
    }

    .system-title {
        color: #fff;
        font-size: 1.6rem;
        font-weight: 600;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    // 移动端适配：调整尺寸
    @media (max-width: 768px) {
        padding: 1.5rem;
        .login-logo {
            width: 40%;
            margin-bottom: 1rem;
        }
        .system-title {
            font-size: 1.4rem;
        }
    }
}

// 表单区域
.form-section {
    flex: 1.2; 
    padding: 2.5rem;
    display: flex;
    flex-direction: column;
    justify-content: center;

    // 移动端适配
    @media (max-width: 768px) {
        padding: 1.5rem;
        flex: none;
    }
}

// 登录表单样式
.login-form {
    width: 100%;
    max-width: 350px;
    margin: 0 auto;

    // 输入框聚焦样式增强
    .el-input__wrapper {
        &:focus-within {
            box-shadow: 0 0 0 2px rgba(100, 100, 100, 0.1);
        }
    }
}

.form-actions {
    .el-form-item__content{
         display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 0.5rem;
    }
   

    .remember-checkbox {
        font-size: 0.9rem;
        color: #666;
    }

    .forgot-btn {
        font-size: 0.9rem;
        color: #666;
        padding: 0;
        height: auto;

        &:hover {
            color: #409eff;
        }
    }
}

// 提交按钮区域
.submit-section {
    margin-top: 1.5rem;
}

.login-submit {
    width: 100%;
    height: 40px;
    font-size: 1.1rem;
    background-color: #409eff;
    border-color: #409eff;

    &:hover {
        background-color: #66b1ff;
        border-color: #66b1ff;
    }
}

// 响应式字体适配
@media (max-width: 768px) {
    html {
        font-size: 14px;
    }
}

@media (min-width: 1200px) {
    html {
        font-size: 16px;
    }
}
</style>
